<template>
  <el-container>
    <el-aside width="258px">
      <side_tree :data="userDept" :typeName="'用户管理'" :type="'user'" :default="groupItem.deptId" v-on:childtofather="treeNode" />
    </el-aside>
    <el-main>
      <el-col :span="24" class="flex flex-justify clear" style="border-bottom: 1px solid #eee;padding-bottom: 10px">
        <!--名称-->
        <h1>{{groupItem.deptName}}的所有用户</h1>
        <!--按钮-->
        <el-col :span="18" class="flex flex-right">
          <!--按钮-->
          <el-col :span="18" class="flex flex-right">
             <el-button size="small" type="primary" @click="upLoadModal=true" ><i class="fa fa-upload"></i> 导入用户</el-button>
             <el-button v-if="roleIdList.includes(6)" size="small" type="warning" @click="addModal=true" style="margin-right:20px;margin-left:10px;"><i class="fa fa-plus"></i> 创建用户</el-button>
          </el-col>
        </el-col>
      </el-col>
      <!--部门信息 表单-->
      <el-form size="small" class="from-box" label-width="80px">
        <el-col :span="6">
          <el-form-item label="姓名">
            <el-input v-model="queryCondition" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button size="small" @click="getConditions" type="primary">
            <i class="fa fa-save"></i> 查询
          </el-button>
        </el-col>
      </el-form>
      <el-table ref="table" :data="tableData" style="width: 100%" :max-height="client.height-102-50-20-80-32-110" highlight-current-row
        @cell-mouse-enter="handleCurrentChange" @cell-mouse-leave="removeCurrentChange">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form :model="updateForm" :rules="rules" ref="updateForm" size="small" label-width="90px">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model.trim="updateForm.name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="用户名" prop="userName">
                    <el-input v-model.trim="updateForm.userName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="重置密码" prop="initPassword">
                    <el-switch
                      v-model="isInitPassword"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="职位" prop="job">
                    <el-input v-model.trim="updateForm.job">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否高管" prop="isManager">
                    <el-switch
                      v-model="updateForm.isManager"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="办公电话" prop="tel">
                    <el-input v-model="updateForm.tel"></el-input>
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="移动电话" prop="phone">
                    <el-input v-model="updateForm.phone"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="电子邮件" prop="email">
                    <el-input v-model="updateForm.email"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="角色" prop="roleIds">
                    <el-select v-model="updateForm.roleIds" multiple style="width: 100%">
                      <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="组角色" prop="virRoleIds">
                    <el-select v-model="updateForm.virRoleIds" disabled multiple style="width: 100%">
                      <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="部门" prop="unit">
                    <el-cascader :options="userRealDept" :props="defaultProps" change-on-select v-model="updateForm.unit" :show-all-levels="false"
                      style="width: 100%">
                    </el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" size="small" label-width="90px">
              <el-row>
                <el-col :span="12">
                  <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'虚拟部门' + (index+1)" :key="domain.key" :prop="'domains.' + index + '.value'"
                    :rules="{
                            message: '请选择虚拟部门', trigger: 'blur'
                        }">
                    <el-col :span="12">
                      <el-cascader :options="userDept" :props="defaultProps" change-on-select v-model="domain.value" :show-all-levels="false" style="width: 100%">
                      </el-cascader>
                    </el-col>
                    <el-col :span="4">
                      <el-button @click.prevent="removeDomain(domain)">删除</el-button>
                    </el-col>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="addDomain">新增虚拟部门</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-col :span="24" class="operate_submit">
              <div>
                <el-button type="info" size="small" class="table_ok" @click="updateUserInfo">确定</el-button>
              </div>
              <div>
                <el-button type="info" size="small" class="table_cancel" @click="recover(props.row)">取消</el-button>
              </div>
            </el-col>
          </template>
        </el-table-column>
        <el-table-column label="序号" prop="fNum" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="姓名" prop="name" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="用户名" prop="userName" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="工作电话" prop="tel" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="移动电话" prop="mobile" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="邮箱" prop="email" show-overflow-tooltip>
        </el-table-column>
        <el-table-column min-width="160">
          <template slot-scope="scope">
            <div class="table_operate" v-if="currentRow === scope.row.userId">
              <el-button-group>
                <el-button v-if="roleIdList.includes(7)" class="table_operate_btn table_show" @click.native.prevent="rowExpansion(scope.row)"
                  type="text" size="small">
                <i class="fa fa-edit"></i>  修改
                </el-button>
                <el-button v-if="roleIdList.includes(8)" class="table_operate_btn table_delete" @click.native.prevent="deleteRow(scope.row.userId, scope.row.name)"
                  type="text" size="small">
                <i class="fa fa-trash-o"></i>  移除
                </el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block page_detail">
        <el-pagination @current-change="handlePageCurrentChange" :current-page.sync="pageCurrent" :page-size="pageSize" layout="prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-main>
    <AddModal :addModal="addModal" :roleList="roleList" :treeData="userDept" :realTreeData="userRealDept" @closeModal="closeModal" @addFinish="addFinish"
    />
    <UpLoadModal :upLoadModal="upLoadModal" :header="headers" @closeUpload = "closeUpload"></UpLoadModal>
  </el-container>
</template>

<script>
import side_tree from "../aside";
import AddModal from "./addModal";
import UpLoadModal from "./uploadModal";
import { dataSort, formCheck, deepClone, trim } from "../../../lib/utils";
import { userManagement } from "../../../service/service_zbw";
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState({
      client: state => state.client,
      userDept: state => state.userDept,
      userRealDept: state => state.userRealDept,
      roleList: state => state.roleList,
      roleIdList: state => state.roleIdList
    })
  },
  components: {
    side_tree,
    AddModal,
    UpLoadModal
  },
  data() {
    //办公电话校验
    const checkTel = (rule, value, callback) => {
      //let reg = /^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/;
      let reg = /^0\d{2,3}-?\d{7,8}$/;
      let str = trim(value);
      if(!str){
        callback();
      }
      if (!reg.test(str)) {
        return callback(new Error("座机号码格式不正确"));
      }
      callback();
      
    };
    //手机校验
    const checkPhone = (rule, value, callback) => {
      let reg = /^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/;
      let str = trim(value);
      if (!str) {
        return callback(new Error("手机号码不能为空"));
      } else {
        if (!reg.test(str)) {
          return callback(new Error("手机号码格式不正确"));
        }
        callback();
      }
    };
    //邮箱校验
    const checkEmail = (rule, value, callback) => {
      let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      let str = trim(value);
      if(!str){
        callback();
      }
      if (!reg.test(str)) {
        return callback(new Error("邮箱地址格式不正确"));
      }
      callback();

    };
    return {
      isInitPassword: false,//标记是否重置密码
      groupItem: {
        label: "西部机场集团",
        id: [1]
      },
      queryCondition: "",
      updateForm: {
        name: "",
        userName: "",
        pass: "",
        unit: [],
        roleIds: [],
        job: "",
        tel: "",
        phone: "",
        email: "",
        isManager: false
      },
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'x-access-token': sessionStorage.getItem('USERTOKEN') ? sessionStorage.getItem('USERTOKEN') : '',
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入用户真实姓名",
            trigger: "blur"
          },
          {
            min: 1,
            max: 10,
            message: "长度不超过10个字符",
            trigger: "blur"
          }
        ],
        userName: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "blur"
          },
          {
            min: 1,
            max: 20,
            message: "长度不超过20个字符",
            trigger: "blur"
          }
        ],
          pass: [
            {
              min: 1,
              max: 15,
              message: '密码长度不大于15个字符',
              trigger: 'blur'
            }
          ],
        unit: [
          {
            type: "array",
            required: true,
            message: "请选择部门",
            trigger: "change"
          }
        ],
        roles: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个角色",
            trigger: "change"
          }
        ],
        job: [
          {
            required: true,
            message: "请输入用户职位",
            trigger: "blur"
          },
          {
            min: 1,
            max: 10,
            message: "长度不超过10个字符",
            trigger: "blur"
          }
        ],
        tel: [
          {
            required: false,
            validator: checkTel,
            trigger: "blur"
          }
        ],
        phone: [
          {
            required: true,
            validator: checkPhone,
            trigger: "blur"
          }
        ],
        email: [
          {
            required: false,
            validator: checkEmail,
            trigger: "blur"
          }
        ]
      },
      dynamicValidateForm: {
        domains: [
          {
            value: []
          }
        ]
      },
      tableData: [],
      defaultProps: {
        value: "deptId",
        label: "deptName"
      },
      addModal: false,
      upLoadModal:false,
      total: 0,
      currentRow: "",
      pageCurrent: 1,
      pageSize: 50,
      isUpdate: true,
      show: false,
      lastSelectRow: null,
      CopydynamicValidateForm: null,
      copyUpdateForm: null
    };
  },
  methods: {
    init() {
      this.groupItem = deepClone(this.userDept[0]);
      console.log(this.groupItem);
      this.getConditions();
      //alert(this.uploadModal)
    },
    upload(err){
      alert(err)
    },
    /**
       * 整理查询条件
       */
    getConditions() {
      let param = {
        pageCurrent: this.pageCurrent,
        pageSize: this.pageSize,
        deptId: this.groupItem.deptId,
        userName: this.queryCondition
      };
      if (param.userName !== "") {
        param.pageCurrent = 1;
      }
      this.getTableData(param);
    },
    /**
       * 获取表格数据
       */
    async getTableData(param) {
      let res = await userManagement.getPersonByDept(param);
      if (res.success) {
        this.total = res.obj.itemTotal;
        this.tableData = dataSort(res.obj.items, this.pageCurrent);
        this.queryCondition = "";
      } else {
        this.total = 0;
        this.tableData = [];
        this.$message({
          message: res.msg,
          type: "error"
        });
      }
    },
    /**
       * 修改人员信息
       */
    async updateUserInfo() {
      //判断环境是否支持 crypto 模块
      // let crypto;
      // try {
      //   crypto = require('crypto');
      // } catch (err) {
      //   console.log('不支持 crypto!');
      // }
      // //md5加密
      // let hashPass = crypto.createHmac('md5', this.updateForm.pass)
      //   .digest('hex');
      let flag = formCheck(this, 'updateForm');
      if(!flag) {
          return;
      }
      let param = {
        name: this.updateForm.name,
        userName: this.updateForm.userName,
        passwd: this.isInitPassword === true ? "" : null,
        roleIds: this.updateForm.roleIds,
        position: this.updateForm.job,
        tel: this.updateForm.tel,
        mobile: this.updateForm.phone,
        email: this.updateForm.email,
        userId: this.updateForm.userId,
        isManager: this.updateForm.isManager,
        deptIds: []
      };
      param.deptIds.push(this.updateForm.unit[this.updateForm.unit.length - 1]);
      if (this.dynamicValidateForm.domains.length > 0) {
        for (let i of this.dynamicValidateForm.domains) {
          if (i.value[0] && i.value[0] !== "") {
            param.deptIds.push(i.value[i.value.length - 1]);
          }
        }
      }
      let res = await userManagement.update(param);
      if (res.success) {
        this.getConditions();
        this.$message({
          message: res.msg,
          type: "success"
        });
      } else {
        this.$message({
          message: res.msg,
          type: "error"
        });
      }
    },
    /**
       * 通过详情按钮控制表格展开或闭合
       */
    rowExpansion(row) {
      console.log(row);
      this.isInitPassword = false; //默认不重置密码
      this.lastSelectRow = row;
      this.$refs.table.toggleRowExpansion(row, true);
      this.updateForm = {
        name: row.name,
        userName: row.userName,
        pass: "",
        unit: row.deviceDesc,
        roleIds: row.roleIds,
        virRoleIds: row.virRoleIds,
        job: row.position,
        tel: row.tel,
        phone: row.mobile,
        email: row.email,
        userId: row.userId,
        isManager: row.isManager
      };
      this.getDeptByPerson(row.userId);
    },
    async getDeptByPerson(param) {
      let res = await userManagement.getDeptByPerson(param);
      if (res.success) {
        this.updateForm.unit = res.obj.realDeptId;
        if (res.obj.virDeptIds) {
          this.dynamicValidateForm.domains = [];
          for (let i of res.obj.virDeptIds) {
            let obj = {
              value: i,
              key: Date.now()
            };
            this.dynamicValidateForm.domains.push(obj);
          }
        }
      }
    },
    recover(val) {
      this.$refs.table.toggleRowExpansion(val, false);
    },
    /**
       * hover表格某一行获取id
       */
    handleCurrentChange(val) {
      //当删除当前行时,val值不存在
      try {
        this.currentRow = val.userId;
      } catch (error) {
        this.currentRow = "";
      }
    },
    removeCurrentChange() {
      this.currentRow = "";
    },
    /**
       * 分页改变
       */
    handlePageCurrentChange(val) {
      this.pageCurrent = val;
      this.getConditions();
    },
    /**
       * 编辑，保存，修改
       */
    chosen(val, id) {
      console.log(this.groupItem.id.pop());
    },
    /**
       * 删除
       */
    deleteRow(id, name) {
      this.$confirm("您确定要删除用户“" + name + "”吗？", "询问", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          this.delete(id);
        })
        .catch(() => {
          //TODO
        });
    },
    async delete(param) {
      let res = await userManagement.del(param);
      if (res.success) {
        this.getConditions();
        this.$message({
          type: "success",
          message: res.msg
        });
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
    },
    /**
       * 接收树组件传递过来的数据，obj是节点对象
       */
    treeNode(obj) {
      //赋值给data
      this.groupItem = deepClone(obj);
      this.getConditions();
    },
    /**
       * 新增成功
       */
    addFinish() {
      this.getConditions();
    },
    /**
       * 关闭模态框
       */
    closeModal(val) {
      this.addModal = val;
    },
    closeUpload(val) {
      this.upLoadModal = val;
    },
    /**
       * 新增一条虚拟部门
       */
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: [],
        key: Date.now()
      });
    },
    /**
       * 删除一条虚拟部门
       */
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },
    /**
     *
     */
     handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
  },
  watch: {
    lastSelectRow(newval, oldval) {
      this.$refs.table.toggleRowExpansion(oldval, false);
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style scoped>
h1 {
  width: 25%;
  font-weight: bold;
  color: #666666;
  font-size: 18px;
}

.table_show,
.table_show:link,
.table_show:visited,
.table_show:hover,
.table_show:active {
  background: #535953;
  color: #fff;
}

.table_delete,
.table_delete:link,
.table_delete:visited,
.table_delete:hover,
.table_delete:active {
  background: #d9524e;
  color: #fff;
}

.table_ok {
  width: 80px;
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}

.table_cancel {
  width: 80px;
  background: #d8d8d8;
  color: #666;
  border: 1px solid #999;
}
</style>

